import axios from '../js_sdk/xtshadow-axios/axios.min'
import store from '../store'
import {
	paramsToStr,
	toast
} from './tools'

import {
	baseURL,
	suiteIds
} from '../config/app'


function checkParams(params) {
	if (typeof params != 'object') return params
	for (let key in params) {
		const value = params[key];
		if (value === null || value === undefined || value === "") {
			delete params[key];
		}
	}
	return params;
}

const spIgnore = ['该用户是团队负责人，不能把该用户从团队成员中删除','团队ID不能为空','团队数字医生工作室使用人不能为空！'] //在此数组里的，会忽略掉返回错误信息
function remove() {
	uni.removeStorageSync('token')
	uni.removeStorageSync('userinfo')
	uni.removeStorageSync('qw')
	uni.removeStorageSync('isLogin')
	uni.removeStorageSync('zhichengName')
	uni.removeStorageSync('qrUrl')
	uni.removeStorageSync('myTeam')
	uni.removeStorageSync('code')
	//uni.removeStorageSync('redirect')
}
async function howShowToast(response) {
	// const pages = getCurrentPages()[0];
	// const arr = ['/pages/index/index']
	//if(arr.includes('/pages/index/index'))return    //首页不用弹窗
	const Store = uni.getStorageSync('token');
	//console.log(pages.$page.fullPath);
	//&&pages.$page.fullPath !== '/pages/login/index'
	//if(!Store)return     //没有token，不报错误
	
	// const pagesHandle = getCurrentPages(); // 获取当前页面栈
	// console.log(pagesHandle,'pagesHandle',window.location.href);
	//this.$u.toast(window.location.href)
	
	if (response.data.code == 401) {  //401的时候，重新登录
		//alert(window.location.href,res,'res')
		uni.showToast({
			title: '您还未登录，请登录后体验功能!',
			icon: "none"
		})
		const t = setTimeout(() => {
			remove()
			clearTimeout(t)
			uni.navigateTo({
				url: '/pages/login/auth'
			})
		}, 1500)
		return
	} 
	
	//console.log(response,'response');
	if (response.data.code !== 200 && !spIgnore.includes(response.data.msg)) {
		uni.showToast({
			title: response.data.msg,
			icon: "none",
			duration:3000
		})
		//this.$u.toast()
	}
}

const service = axios.create({
	baseURL: baseURL,
	timeout: 8000,
	header: {
		'content-type': 'application/json;charset:utf-8'
	},

});

const ignore = ['/business/team/getTeamByUser', 'getInfo','/business/customer/synchronousCustomerInfo'] //在此数组里的，会忽略掉加载图标
function findArrString(url) {
	let findstring = ignore.find(v => url.search(v) !== -1)
	if (findstring) {
		return true
	} else {
		return false
	}
}
// request拦截器
service.interceptors.request.use(
	config => {
		//console.log(config);
		config.data = checkParams(config.data)
		config.params = checkParams(config.params)
		if (config.method == 'GET') {
			config.url += paramsToStr(config.params)
		}
		const Store = uni.getStorageSync('token');
		//const pages = getCurrentPages()[0];
		if (Store) { //没有token就不发送token
			config.header.Authorization = 'Bearer ' + Store.token
			config.header.Cookie = 'sidebarStatus=0; Admin-Token=' + Store.token
		}

		//console.log(config);
		//if(!ignore.includes(config.url)){  //首页验证码不加载，因为错误后会加载会覆盖掉错误信息弹窗
		if (!findArrString(config.url)) {
			uni.showLoading({
				title: "加载数据中"
			})
		}
		//console.log(config);
		//WXlogin()
		return config
	},
	error => {
		//uni.hideLoading()
		// Do something with request error
		//console.log(error) // for debug
		Promise.reject(error)
	}
)

// response 拦截器
service.interceptors.response.use(
	async (response) => {
			//console.log(response,12331);
			uni.hideLoading()
			howShowToast(response)
			//console.log(response,'response');
			return Promise.resolve(response.data)
		},
		error => {
			//console.log(error, 'error');
			//if(response.data.code !== 200){
			uni.hideLoading()
			//&& !spIgnore.includes(config.url)
			//if (error.response.data.message) {
			if (!error.response) { //超时
				uni.showToast({
					title: "网络超时，请重新尝试",
					icon: "none"
				})
			} else {
				console.log(error,777);
				//if()
				
				uni.showToast({ //响应错误
					title: error.response.data.message,
					icon: "none",
					duration:3000
				})
			}
			//}
			//this.$u.toast()
			//}
			//console.log(error)
			//console.log('err' + error) // for debug
			return Promise.reject(error)
		}
)

export default service